package com.lagou.service.impl;

import com.lagou.dao.TokenDao;
import com.lagou.dao.UserDao;
import com.lagou.feign.CodeFeignClient;
import com.lagou.pojo.LagouToken;
import com.lagou.pojo.LagouUser;
import com.lagou.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.stereotype.Service;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Optional;
import java.util.UUID;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserDao userDao;
    @Autowired
    private TokenDao tokenDao;
    @Autowired
    private CodeFeignClient codeFeignClient;

    /**
     * 注册接口：-1后台服务异常 0.成功 1.验证码错误 2.验证码超时 3.未发送过验证码 4.邮箱已经注册
     *
     * @param email
     * @param password
     * @param code
     * @return
     */
    @Override
    public String register(String email, String password, String code, HttpServletResponse response) {

        //首先校验知否已经注册
        boolean registered = isRegistered(email);
        if (registered) {
            return "4";
        }
        //校验验证码是否正确，0正确 1错误 2超时 3未发送过验证码 ，null表示服务调用异常
        String validate = codeFeignClient.validate(email, code);
        if (validate == null) {
            return "-1";
        }
        if (!"0".equals(validate)) {
            return validate;
        }
        LagouUser lagouUser = new LagouUser();
        lagouUser.setPassword(password);

        String time = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
        lagouUser.setCreateTime(time);
        lagouUser.setUpdateTime(time);
        lagouUser.setEmail(email);
        //保存用户注册信息
        userDao.save(lagouUser);
        //生成并保存token
        saveToken(email, response);
        return "0";
    }

    /**
     * 判断邮箱是否已经注册,true代表已经注册过，false代表尚未注册
     *
     * @param email
     * @return
     */
    @Override
    public boolean isRegistered(String email) {
        LagouUser lagouUser = new LagouUser();
        lagouUser.setEmail(email);
        Example<LagouUser> example = Example.of(lagouUser);
        //查询
        Optional<LagouUser> one = userDao.findOne(example);
        if (one.isEmpty()) {
            return false;
        }
        return true;
    }

    /**
     * 根据token查询用户登录邮箱接口
     *
     * @param token
     * @return
     */
    @Override
    public String info(String token) {
        LagouToken lagouToken = new LagouToken();
        lagouToken.setToken(token);
        Example<LagouToken> example = Example.of(lagouToken);
        //查询
        Optional<LagouToken> one = tokenDao.findOne(example);
        if (one.isEmpty()) {
            return null;
        }
        LagouToken result = one.get();
        return result.getEmail();
    }

    /**
     * 登录，成功返回0，错误返回1
     *
     * @param email
     * @param password
     * @param response
     * @return
     */
    @Override
    public boolean login(String email, String password, HttpServletResponse response) {
        LagouUser lagouUser = new LagouUser();
        lagouUser.setEmail(email);
        Example<LagouUser> example = Example.of(lagouUser);
        //查询
        Optional<LagouUser> one = userDao.findOne(example);
        if (one.isEmpty() || !one.get().getPassword().equals(password)) {
            return false;
        }
        saveToken(email, response);
        return true;
    }

    /**
     * 存储token并存到cookie中
     *
     * @param email
     * @param response
     */
    private void saveToken(String email, HttpServletResponse response) {
        String token = UUID.randomUUID().toString();
        LagouToken lagouToken = new LagouToken();
        lagouToken.setEmail(email);
        lagouToken.setToken(token);
        //保存token
        tokenDao.save(lagouToken);
        Cookie tokenCookie = new Cookie("token", token);
        tokenCookie.setPath("/"); // 默认路径
        Cookie emailCookie = new Cookie("email", email);
        emailCookie.setPath("/"); // 默认路径
        response.addCookie(tokenCookie);
        response.addCookie(emailCookie);
    }
}
